package view;

import dao.Blog;
import dao.BlogDao;
import dao.User;
import dao.UserDao;
import org.thymeleaf.TemplateEngine;
import org.thymeleaf.context.WebContext;

import javax.servlet.ServletContext;
import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;
import java.io.IOException;
import java.sql.SQLException;

@WebServlet("/blogDetails.html")
public class BlogDetails extends HttpServlet {
    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        if (req.getSession(false) == null){
            resp.sendRedirect("login.html");
            return;
        }

        HttpSession session = req.getSession();
        User user = (User) session.getAttribute("user");

        resp.setContentType("text/html;charset=utf-8");
        String blogId = req.getParameter("blogId");
        if (blogId == null){
            resp.sendRedirect("blogList.html");
            return;
        }
        BlogDao blogDao = new BlogDao();
        try {
            Blog blog = blogDao.selectOne(Integer.parseInt(blogId));
            ServletContext context = this.getServletContext();
            TemplateEngine engine = (TemplateEngine) context.getAttribute("engine");
            WebContext webContext = new WebContext(req,resp,context);
            webContext.setVariable("blog",blog);
            webContext.setVariable("isDelete",blog.getUserId() == user.getUserId());
            String html = engine.process("blogDetails",webContext);
            System.out.println(html);
            resp.getWriter().write(html);
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
